package com.fengxu.gamescript.jsengine.api.music;

import android.content.Context;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.SoundPool;
import com.fengxu.gamescript.jsengine.api.AbstractJsObject;
import com.fengxu.gamescript.jsengine.api.Global;

/**
 * 音乐，自动点击抽象类
 */
public abstract class AbstractMusicAutoClick extends AbstractJsObject implements IAutoMusic {

    /**
     * 最大支持的音乐索引数量
     */
    public static final int MaxMusicNum = 21;


    /**
     * 音频池
     */
    protected SoundPool soundPool;


    /**
     * 音乐对应的音频池中的索引
     */
    protected int[] musicIdIndex = new int[MaxMusicNum];

    /**
     * 音频流是否加载完成
     */
    protected boolean[] musicLoadedStatus = new boolean[24];



    public AbstractMusicAutoClick(Global global) {
        super(global);
        // 初始化soundPool
        AudioAttributes.Builder builder = new AudioAttributes.Builder();
        builder.setLegacyStreamType(AudioManager.STREAM_MUSIC);
        soundPool = new SoundPool.Builder()
                    .setMaxStreams(21)
                    .setAudioAttributes(builder.build())
                    .build();
        // 加载声音资源
        loadMusicResource();
    }

    /**
     * 加载音乐资源
     */
    private void loadMusicResource(){
        Context context = global.getmContext();
        for (int i = 0; i < MaxMusicNum; i++) {
            int resId = context.getResources().getIdentifier("m"+(i+1),"raw",context.getPackageName());
            musicIdIndex[i] = soundPool.load(context,resId,1);
        }
        soundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
            @Override
            public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
                if(status != 0) return;
                int index = 0;
                for (int i = 0; i < musicIdIndex.length; i++) {
                    if(musicIdIndex[i] == sampleId){
                        index = i;
                    }
                }
                // 标注该索引处的资源加载完成
                musicLoadedStatus[index] = true;
            }
        });
    }


    /**
     * @param index 总索引，从上到下，从做到右
     */
    @Override
    public void playMusic(int index) {
        while (!musicLoadedStatus[index]){
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        // 音频加载完成后，才可播放
        int id = musicIdIndex[index];
        soundPool.play(id,1,1,1,0,2.0F);
    }

    /**
     * 释放音乐流资源
     */
    protected void releaseMusic(){
        for (int i = 0; i < musicLoadedStatus.length; i++) {
            if(musicLoadedStatus[i]){
                soundPool.unload(musicIdIndex[i]);
            }
        }
        soundPool.release();
    }

}
